#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from itsdangerous import TimedJSONWebSignatureSerializer as serialzier, BadData
from django.conf import settings
from oauth.constants import ACCESS_TOKEN_EXPIRES


def generate_access_token(openid):
    """
    :param openid: 加密的openid值
    :return: token的秘闻
    """
    # 创建序列化对象
    s = serialzier(settings.SECRET_KEY, ACCESS_TOKEN_EXPIRES)
    # 准备序列化数据
    data = {'openid': openid}
    # 调用dumps方法加密
    token = s.dumps(s)
    # 返回加密后的数据
    return token.decode()


def check_access_token(openid):
    """
    :param openid:
    :return:
    """
    # 创建序列化对象
    s = serialzier(settings.SECRET_KEY, ACCESS_TOKEN_EXPIRES)
    # 调用dumps方法解密
    try:
        data = s.load(openid)
    except BadData:
        return None
    else:
        return data.get('openid')
